package kr.pfg.socialproject
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kr.pfg.socialproject.config.Config;
	import kr.pfg.socialproject.error.ProjectError;
	import kr.pfg.socialproject.events.LatestVersionEvent;
	import kr.pfg.socialproject.utils.URIUtil;
	
	[Event ( name = "checkVersion", type = "kr.pfg.socialproject.events.LatestVersionEvent" ) ]
	[Event ( name = "checkVersionFail", type = "kr.pfg.socialproject.events.LatestVersionEvent" ) ]
	
	public class SocialProject extends Sprite
	{
		protected var projectName: String;
		
		public function SocialProject()
		{
			// check project name.
			this.checkName();
			
			this.initStage();
		}
		
		private function checkName(): void
		{
			if( this.projectName == null )
				throw new ProjectError( ProjectError.ERROR_1001 );
		}
		
		private function initStage(): void
		{
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;
		}
		
		/**
		 * Check Latest Version 
		 */		
		 
		private var versionLoader: URLLoader;
		private var versionURL: String;
		public function checkLatestVersion(): void
		{
			this.versionLoader = new URLLoader();
			this.versionLoader.addEventListener( Event.COMPLETE, checkLatestVersionComplete );
			this.versionLoader.addEventListener( IOErrorEvent.IO_ERROR, checkLatestVersionFail );
			this.versionLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, checkLatestVersionSecurityFail );
			
			this.versionURL = URIUtil.mergeParameterToURI( Config.PATH_GET_VERSION, { name: this.projectName } );
			
			this.versionLoader.load( new URLRequest( this.versionURL ) );
		}
		
		private function checkLatestVersionComplete( e: Event ): void
		{
			this.dispatchEvent( new LatestVersionEvent( LatestVersionEvent.CHECK_VERSION, "", this.versionLoader.data as String ) );
		}
		
		private function checkLatestVersionFail( e: IOErrorEvent ): void
		{
			this.dispatchEvent( new LatestVersionEvent( LatestVersionEvent.CHECK_VERSION_FAIL, "unable to find url : " + Config.PATH_GET_VERSION ) );
		}
		
		private function checkLatestVersionSecurityFail( e: SecurityErrorEvent ): void
		{
			this.dispatchEvent( new LatestVersionEvent( LatestVersionEvent.CHECK_VERSION_FAIL, "unable to load by security error." ) );
		}
	}
}